# -*- coding: utf-8 -*-
"""配置管理模块"""

import yaml
from pathlib import Path
import os

class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_path="config.yaml"):
        self.config_path = Path(config_path)
        if not self.config_path.is_absolute():
            # 如果是相对路径，基于当前文件所在目录的父目录
            base_dir = Path(__file__).parent.parent
            self.config_path = base_dir / config_path
        self._config = None

    def get_config(self):
        """获取配置"""
        if self._config is None:
            if not self.config_path.exists():
                raise FileNotFoundError(f"配置文件不存在: {self.config_path}")
            with open(self.config_path, "r", encoding="utf-8") as f:
                self._config = yaml.safe_load(f)
        return self._config
    
    def reload_config(self):
        """重新加载配置"""
        self._config = None
        return self.get_config()
    
    def get_doubao_config(self, key_id=None):
        """获取豆包配置"""
        config = self.get_config()
        doubao_config = config.get("doubao", {})
        
        if key_id is None:
            key_id = doubao_config.get("default_key", "key1")
        
        keys = doubao_config.get("keys", {})
        if key_id not in keys:
            raise ValueError(f"豆包密钥配置不存在: {key_id}")
        
        return keys[key_id]
    
    def get_doubao_key_config(self, key_id=None):
        """获取豆包密钥配置（别名方法，兼容父项目）"""
        return self.get_doubao_config(key_id)
    
    def get_deepseek_config(self):
        """获取DeepSeek配置"""
        config = self.get_config()
        return config.get("deepseek", {})
    
    def get_feishu_config(self):
        """获取飞书配置"""
        config = self.get_config()
        return config.get("feishu", {})
    
    def get_gitlab_config(self):
        """获取GitLab配置"""
        config = self.get_config()
        return config.get("gitlab", {})
    
    def get_output_config(self):
        """获取输出配置"""
        config = self.get_config()
        return config.get("output", {})
    
    def get_prompt_template(self, template_name):
        """获取提示词模板"""
        config = self.get_config()
        prompts = config.get("prompts", {})
        return prompts.get(template_name, "")
    
    def get_prompt_from_file(self, prompt_file_key):
        """从文件加载提示词
        
        Args:
            prompt_file_key: 配置中的提示词文件路径键名，如 'test_case_prompt_file'
        
        Returns:
            提示词内容字符串
        """
        config = self.get_config()
        prompts = config.get("prompts", {})
        
        # 获取文件路径
        prompt_file = prompts.get(prompt_file_key)
        if not prompt_file:
            # 如果没有文件配置，尝试使用内联模板
            template_key = prompt_file_key.replace('_file', '')
            return prompts.get(template_key, "")
        
        # 构建完整路径
        prompt_path = Path(prompt_file)
        if not prompt_path.is_absolute():
            base_dir = Path(__file__).parent.parent
            prompt_path = base_dir / prompt_file
        
        # 读取文件
        try:
            with open(prompt_path, 'r', encoding='utf-8') as f:
                return f.read()
        except FileNotFoundError:
            print(f"警告: 提示词文件不存在: {prompt_path}")
            # 返回内联模板作为后备
            template_key = prompt_file_key.replace('_file', '')
            return prompts.get(template_key, "")

# 全局配置管理器实例
config_manager = ConfigManager()

